package zezutom.designpatterns.cor;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * Accepts client requests and triggers the evaluation process.
 * Promotes loose coupling among RequestHandler implementations.
 * 
 * @author tomasz
 */
public class RequestHandlerGateway {

    private static RequestHandlerGateway instance;
    
    private ServiceLoader<RequestHandler> loader;
    
    private RequestHandlerGateway() {
        loader = ServiceLoader.load(RequestHandler.class);
    }
    
    public static synchronized RequestHandlerGateway getInstance() {
        if (instance == null) {
            instance = new RequestHandlerGateway();
        }
        return instance;
    }
        
    public boolean handleRequest(LoanRequest request) {
        boolean approved = false;
        
        Iterator<RequestHandler> handlers = loader.iterator();
        
        while(!approved && handlers.hasNext()) {
            approved = handlers.next().handleRequest(request);
        }
        
        return approved;
    }    
}
